package com.huikeportal.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huikeportal.controller.common.Tools;
import com.huikeportal.model.DpModel;
import com.huikeportal.model.GcModel;
import com.huikeportal.model.QyModel;
import com.huikeportal.model.SiteAllInfo;
import com.huikeportal.model.SiteCommon;
import com.huikeportal.model.SiteSelectParam;
import com.huikeportal.model.UserInfo;
import com.huikeportal.model.UserSiteHistory;
import com.huikeportal.model.common.SqlParameter;
import com.huikeportal.service.LoginService;
import com.huikeportal.service.SelectSiteService;

@Controller
public class SelectSiteController {

	@Autowired
	private HttpSession session;

	@Autowired
	private LoginService loginService;

	@Autowired
	private SelectSiteService selectSiteService;

	@InitBinder("siteSelectParam")
	public void initBinder(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("siteSelectParam.");
	}

	/**
	 * 场所选择
	 * 
	 * @param siteSelectParam
	 *            传入参数
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/siteSelect")
	public String siteSelect(SiteSelectParam siteSelectParam, ModelMap model)
			throws Exception {
		String flag = "0";// 用以区分是从报表进入还是更换广场进入(0表示从报表进入)
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);
		String menuHtml = loginService.getMenuHtml(userInfo, siteSelectParam
				.getPageFrom());
		SiteAllInfo gcSiteInfo = new SiteAllInfo();
		// 如果是单选
		if ("1".equals(siteSelectParam.getChoiceType())) {
			model.addAttribute("selectType", "0");
			model.addAttribute("validateFlag", "1");
		}
		// 如果是多选
		else if ("2".equals(siteSelectParam.getChoiceType())) {
			model.addAttribute("selectType", "1");
			model.addAttribute("validateFlag", "1");
		}
		// 如果是随意选
		else if ("3".equals(siteSelectParam.getChoiceType())) {
			// 按照多选的规则
			model.addAttribute("selectType", "1");
			// 不进行场所必选的校验
			model.addAttribute("validateFlag", "0");
		}
		// 如果是单选广场
		if ("1".equals(siteSelectParam.getSelectType())) {
			model.addAttribute("pageTitle", "广场选择");
			// 查询传入场所的信息
			SiteCommon siteInfo = selectSiteService
					.querySiteInfo(siteSelectParam.getGcSiteId());
			model.addAttribute("defaultSelected", siteInfo.getSiteId());// 设置默认选中
			// 获取用户权限下的所有广场信息
			List<SiteAllInfo> gc = loginService.getGcSiteList(userInfo);
			GcModel gcModel = new GcModel();
			gcModel.setGuangchangString(pinjie(gc));
			List<SiteAllInfo> gcList = selectSiteService.getGcList(gcModel);
			// 获取地区列表
			List<GcModel> dqList = selectSiteService.queryDqList(gcModel);
			// 获取商圈列表
			List<GcModel> sqList = selectSiteService.querySqList(gcModel);
			// 获取国家的数据
			String guojiaList = selectSiteService.getGuojiaList();
			model.addAttribute("gc_guoList", guojiaList);
			// 初始化查询广场数据
			model.addAttribute("gcList", gcList);
			if (dqList.size() == 0 || dqList.get(0) == null) {
				model.addAttribute("dqList", null);
			} else {
				model.addAttribute("dqList", dqList);
			}
			if (sqList.size() == 0 || sqList.get(0) == null) {
				model.addAttribute("sqList", null);
			} else {
				model.addAttribute("sqList", sqList);
			}
		}
		// 如果是单选区域
		else if ("2".equals(siteSelectParam.getSelectType())) {
			// 查询传入场所的信息
			SiteCommon siteInfo = selectSiteService
					.querySiteInfo(siteSelectParam.getQySiteId());
			model.addAttribute("defaultSelected", siteInfo.getSiteId());// 设置默认选中
			gcSiteInfo.setSiteid(siteInfo.getParent300());
			gcSiteInfo.setSitename(siteInfo.getName300());
			model.addAttribute("pageTitle", "区域选择");
			String gcId = siteInfo.getParent300();
			// 初始化查询首页的区域
			QyModel qyModel = new QyModel();
			qyModel.setGcSiteId(siteInfo.getParent300());
			// 如果是更换广场
			if (!"".equals(siteSelectParam.getBackGcSiteString())
					&& siteSelectParam.getBackGcSiteString() != null) {
				gcId = siteSelectParam.getBackGcSiteString();
				qyModel.setGcSiteId(gcId);
				flag = "1";
				gcSiteInfo.setSiteid(siteSelectParam.getBackGcSiteString());
				gcSiteInfo.setSitename(selectSiteService.querySiteInfo(
						siteSelectParam.getBackGcSiteString()).getSiteName());
			}
			// 根据传入广场id获取所有楼层
			List<SiteAllInfo> lcList = selectSiteService.queryLcByGc(gcId);
			model.addAttribute("qy_lcList", lcList);
			List<SiteAllInfo> qyList = selectSiteService.queryQyList(qyModel);
			model.addAttribute("qyPageDataVo", qyList);// 初始化查询结果
		}
		// 如果是单选楼层
		else if ("3".equals(siteSelectParam.getSelectType())) {
			// 查询传入场所的信息
			SiteCommon siteInfo = selectSiteService
					.querySiteInfo(siteSelectParam.getLcSiteId());
			model.addAttribute("defaultSelected", siteInfo.getSiteId());// 设置默认选中
			gcSiteInfo.setSiteid(siteInfo.getParent300());
			gcSiteInfo.setSitename(siteInfo.getName300());
			// 设置参数
			SqlParameter sql = new SqlParameter();
			sql.setString(siteInfo.getParent300());// 广场id
			// 如果是更换广场
			if (!"".equals(siteSelectParam.getBackGcSiteString())
					&& siteSelectParam.getBackGcSiteString() != null) {
				sql.setString(siteSelectParam.getBackGcSiteString());
				gcSiteInfo.setSiteid(siteSelectParam.getBackGcSiteString());
				gcSiteInfo.setSitename(selectSiteService.querySiteInfo(
						siteSelectParam.getBackGcSiteString()).getSiteName());
				flag = "1";
			}
			sql.setStringChar(null);// 楼层名称
			List<SiteAllInfo> lcList = selectSiteService.queryLcList(sql);
			model.addAttribute("lcList", lcList);// 初始化查询结果
			model.addAttribute("pageTitle", "楼层选择");// 页面名称
		}
		// 如果是单选店铺
		else if ("4".equals(siteSelectParam.getSelectType())) {
			// 查询传入场所的信息
			SiteCommon siteInfo = selectSiteService
					.querySiteInfo(siteSelectParam.getDpSiteId());
			model.addAttribute("defaultSelected", siteInfo.getSiteId());// 设置默认选中
			gcSiteInfo.setSiteid(siteInfo.getParent300());
			gcSiteInfo.setSitename(siteInfo.getName300());
			// 获取用户的店铺权限
			List<SiteAllInfo> dpSiteList = loginService.getDpSiteList(userInfo);
			model.addAttribute("pageTitle", "店铺选择");
			// 初始化查询店铺信息
			DpModel dpModel = new DpModel();
			dpModel.setGcSiteId(siteInfo.getParent300());
			// 如果是更换广场
			if (!"".equals(siteSelectParam.getBackGcSiteString())
					&& siteSelectParam.getBackGcSiteString() != null) {
				dpModel.setGcSiteId(siteSelectParam.getBackGcSiteString());
				gcSiteInfo.setSiteid(siteSelectParam.getBackGcSiteString());
				gcSiteInfo.setSitename(selectSiteService.querySiteInfo(
						siteSelectParam.getBackGcSiteString()).getSiteName());
				flag = "1";
			}
			dpModel.setDpString(pinjie(dpSiteList));// 设围内置用户场所权限范
			List<SiteAllInfo> dpList = selectSiteService.queryDpList(dpModel);
			// dpList = removeList(dpList);// 去重
			// 根据用户店铺范围查询所有能显示的楼层
			List<SiteAllInfo> lcList = selectSiteService
					.selectLcByDp(pinjie(dpList));
			model.addAttribute("dp_lcList", lcList);
			// 根据用户店铺范围查询所有能显示的品牌
			List<SiteAllInfo> ppList = selectSiteService
					.selectPpByDp(pinjie(dpList));
			model.addAttribute("dp_ppList", ppList);
			model.addAttribute("dpList", dpList);// 初始化查询结果
		}
		model.addAttribute("siteSelectParam", siteSelectParam);
		model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
		model.addAttribute("gcSiteInfo", gcSiteInfo);
		model.addAttribute("flag", flag);// 页面入口类型(0:报表入口；1:更换广场入口)
		return "selectSingleSite";
	}

	/**
	 * List去重
	 * 
	 * @param siteList
	 * @return
	 */
	List<SiteAllInfo> removeList(List<SiteAllInfo> siteList) {
		List<String> listTemp = new ArrayList<String>();
		Iterator<SiteAllInfo> it = siteList.iterator();
		while (it.hasNext()) {
			String a = it.next().getSiteid();
			if (listTemp.contains(a)) {
				it.remove();
			} else {
				listTemp.add(a);
			}
		}
		return siteList;
	}

	/**
	 * 拼接字符串
	 * 
	 * @param siteList
	 * @return
	 */
	private String pinjie(List<SiteAllInfo> siteList) {
		StringBuffer stringBuffer = new StringBuffer("");
		String string = "";
		for (int i = 0; i < siteList.size(); i++) {
			stringBuffer.append(siteList.get(i).getSiteid() + ",");
		}
		if (!"".equals(stringBuffer)) {
			string = stringBuffer.toString().substring(0,
					stringBuffer.length() - 1);
		}
		return string;
	}

	/**
	 * 广场单选-查询
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/searchGcSiteSingle")
	@ResponseBody
	Map<String, Object> searchGcSiteSingle(String diqu, String guojia,
			String sheng, String shi, String qu, String shangquan,
			String guangchang) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);
		// 获取用户权限下的所有广场信息
		List<SiteAllInfo> gc = loginService.getDpGcSiteList(userInfo);
		GcModel gcModel = new GcModel();
		if (!"".equals(diqu) && !"-1".equals(diqu)) {
			gcModel.setDqSiteId(diqu);
		}
		if (!"".equals(guojia) && !"-1".equals(guojia)) {
			gcModel.setCountryId(guojia);
		}
		if (!"".equals(sheng) && !"-1".equals(sheng)) {
			gcModel.setProvinceId(sheng);
		}
		if (!"".equals(shi) && !"-1".equals(shi)) {
			gcModel.setCityId(shi);
		}
		if (!"".equals(qu) && !"-1".equals(qu)) {
			gcModel.setAreaId(qu);
		}
		if (!"".equals(shangquan) && !"-1".equals(shangquan)) {
			gcModel.setSqSiteId(shangquan);
		}
		if (!"".equals(guangchang)) {
			guangchang = URLDecoder.decode(guangchang, "UTF-8");
			gcModel.setGcSiteName(guangchang);
		}
		gcModel.setGuangchangString(pinjie(gc));
		List<SiteAllInfo> gcList = selectSiteService.searchGc(gcModel);
		// 给广场加上是否是自身权限标签，0：不是自己权限范围内的；1：是自己权限范围内的
		List<SiteAllInfo> yuanGcList = loginService.getGcSiteList(userInfo);
		for (int i = 0; i < gcList.size(); i++) {
			if (Tools.isHaveGcPer(yuanGcList, gcList.get(i).getSiteid())) {
				gcList.get(i).setSitestaus(1);
			} else {
				gcList.get(i).setSitestaus(0);
			}
		}
		map.put("gcList", gcList);
		return map;
	}

	/**
	 * ajax单选楼层请求
	 * 
	 * @param gcSiteId
	 * @param lcSiteName
	 * @param gotoPage
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/searchLcSiteSingle")
	@ResponseBody
	public Map<String, Object> searchLcSiteSingle(String gcSiteId,
			String lcSiteName, String gotoPage) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		SqlParameter sql = new SqlParameter();
		sql.setString(gcSiteId);
		if (!"".equals(lcSiteName)) {
			lcSiteName = URLDecoder.decode(lcSiteName, "UTF-8");
			sql.setStringChar(lcSiteName);
		} else {
			sql.setStringChar(null);
		}
		List<SiteAllInfo> lcList = selectSiteService.queryLcList(sql);
		map.put("lcList", lcList);
		return map;
	}

	/**
	 * ajax单选区域请求
	 * 
	 * @param gcSiteId
	 * @param lcSiteId
	 * @param qySiteName
	 * @param gotoPage
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/searchQySiteSingle")
	@ResponseBody
	public Map<String, Object> searchQySiteSingle(String gcSiteId,
			String lcSiteId, String qySiteName) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		QyModel qyModel = new QyModel();
		qyModel.setGcSiteId(gcSiteId);
		if (!"".equals(lcSiteId) && !"-1".equals(lcSiteId)) {
			qyModel.setLcSiteId(lcSiteId);
		}
		if (!"".equals(qySiteName) && qySiteName != null) {
			qySiteName = URLDecoder.decode(qySiteName, "UTF-8");
			qyModel.setQySiteName(qySiteName);
		}
		List<SiteAllInfo> qyList = selectSiteService.queryQyList(qyModel);
		map.put("qyList", qyList);
		return map;
	}

	/**
	 * ajax请求单选店铺
	 * 
	 * @param pp
	 * @param lc
	 * @param dpName
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/searchDpSiteSingle")
	@ResponseBody
	public Map<String, Object> searchDpSiteSingle(String gc, String pp,
			String lc, String dpName) throws Exception {
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		Map<String, Object> map = new HashMap<String, Object>();
		// 获取用户的店铺权限
		List<SiteAllInfo> dpSiteList = loginService.getDpSiteList(userInfo);
		String dpString = "";
		for (int i = 0; i < dpSiteList.size(); i++) {
			dpString += dpSiteList.get(i).getSiteid() + ",";
		}
		if (!"".equals(dpString)) {
			dpString = dpString.substring(0, dpString.length() - 1);
		}
		DpModel dpModel = new DpModel();
		dpModel.setDpString(dpString);
		dpModel.setGcSiteId(gc);
		if (!"".equals(pp) && !"-1".equals(pp)) {
			dpModel.setPpId(pp);
		}
		if (!"".equals(lc) && !"-1".equals(lc)) {
			dpModel.setLcSiteId(lc);
		}
		if (!"".equals(dpName) && !"-1".equals(dpName)) {
			dpName = URLDecoder.decode(dpName, "UTF-8");
			dpModel.setDpSiteName(dpName);
		}
		List<SiteAllInfo> dpList = selectSiteService.queryDpList(dpModel);
		map.put("dpList", dpList);
		return map;
	}

	/**
	 * 单选场所点击确定保存session和更新表
	 * 
	 * @param siteId
	 * @param menuAddress
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/clickSearchResult")
	@ResponseBody
	public Map<String, Object> clickSearchResult(String siteId,
			String menuAddress) throws Exception {
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);
		Map<String, Object> map = new HashMap<String, Object>();
		UserSiteHistory userSiteHistory = selectSiteService.saveSelectResult(
				userInfo, siteId, menuAddress);
		// 更新session
		String sessionId = userSiteHistory.getUserId()
				+ userSiteHistory.getMenuId();
		session.setAttribute(sessionId, userSiteHistory);
		return map;
	}
}
